import React from "react";
import { forwardRef, useState, useEffect, useCallback } from "react";
import Form from '../../Form';

import styles from './context-menu.module.css';


/**
 * MenuContext & MenuProvider
 * 在表格中呼出右键菜单的解决方案
 * 
 * 在MenuProvider中主要维护几个状态，包括菜单编号（MenuID），菜单上下文
 * （context）以及菜单显示的位置（anchor）。向外export一个调用入口即
 * setMenu。
 * 
 * 这个方案并不能将所有的细节包含进来，包括菜单将在何时触发（对于某些元素可
 * 能只有在某些内部状态满足的情况下才会触发，但是这些状态在这里是获取不到的）
 */

const Menu = forwardRef(({state, data, menuSpecs={}}, ref) => {

  const [displayModal, setDisplayModal] = useState(false);
  const [context, setContext] = useState();
  const [menuName, setMenuName] = useState();
  
  const [style, setStyle] = useState({
    top: 0, 
    left: 0, 
    display:'none'
  });

  const on = useCallback((event) => {

    event.preventDefault();
    event.stopPropagation();

    const {path} = event;
    
    let menuContext;
    for (let i = 0; i < path.length; i++) {
      if (Object.keys(menuSpecs).includes(path[i].dataset?.menu)) {
        menuContext = {...path[i].dataset};
      }
    }

    if (menuContext) {
      setMenuName(menuContext.menu);
      setContext(menuContext);
    } else {
      setMenuName();
      setContext();
    }

    setStyle({
      display: 'block',
      top:  event.pageY,
      left: event.pageX,
    })
  }, []);

  const off = useCallback((e) => {
    e.preventDefault();
    setStyle({
      display: 'none',
      top: 0,
      left: 0,
    })
  }, [])

  useEffect(() => {
    
    console.log(ref?.current, 'from menu');

    ref?.current?.addEventListener('contextmenu', on);
    ref?.current?.addEventListener('click', off);

    return () => {

      ref?.current?.removeEventListener('contextmenu', on);
      ref?.current?.removeEventListener('click', off);
      
    }
  }, [])


  const defaultMenu = {
    disabled: {desc: '无可用操作……', disabled: true},
  }

  if(menuSpecs[menuName] === undefined) {
    
    return <></>
    
  } else {

    const menuItemElems = [];
    for (const [key, entry] of Object.entries(menuSpecs[menuName] ?? defaultMenu)) {
      if (entry === 'hr') {
        menuItemElems.push(<hr key={Math.random().toString()}/>);
      } else {

        const {desc, handler=(context)=>{console.log('not implemented', context)}, modal} = entry;

        const itemClickHandler = (e) => {
          handler(context);
          setDisplayModal(modal);
          setStyle({display: 'none', top: 0, left: 0});
        }

        menuItemElems.push(<li key={key} onClick={itemClickHandler}>{desc ?? key}</li>);
      }
    }
    
    return <ul className={styles['menu']} style={style}>
      {menuItemElems}
    </ul>

  }

});

export default Menu;